package com.example.lj.uav.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.example.lj.uav.MyApplication;
import com.example.lj.uav.sqlite.SQLiteDbHelper;
import com.example.lj.uav.utils.TimeUtils;

import java.math.BigDecimal;

import dji.common.flightcontroller.FlightControllerState;
import dji.common.flightcontroller.LocationCoordinate3D;
import dji.sdk.flightcontroller.FlightController;

public class FlightRecorderService extends Service {

    private Recorder recorder;
    private int time;

    @Override
    public void onCreate() {
        super.onCreate();
        recorder = new Recorder(TimeUtils.getDate());
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController != null) {
            //FlightController回调
            flightController.setStateCallback(new FlightControllerState.Callback() {
                @Override
                public void onUpdate(@NonNull FlightControllerState flightControllerState) {
                    if (!flightControllerState.isFlying())
                        return;
                    if (time > flightControllerState.getFlightTimeInSeconds())
                        recorder.save();
                    //飞行时间
                    time = flightControllerState.getFlightTimeInSeconds();
                    recordListener.update(time);
                    recorder.setTime(time);
                    //起飞高度
                    recorder.setTakeoff(flightControllerState.getTakeoffLocationAltitude());
                    //高度
                    LocationCoordinate3D aircraftLocation = flightControllerState.getAircraftLocation();
                    recorder.setHeight(aircraftLocation.getAltitude());
                    //速率
                    float vX = flightControllerState.getVelocityX();
                    float vY = flightControllerState.getVelocityY();
                    float vZ = flightControllerState.getVelocityZ();
                    recorder.setSpeed(vX * vX
                            + vY * vY
                            + vZ * vZ);
                }
            });
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, START_FLAG_REDELIVERY, startId);
    }

    @Override
    public void onDestroy() {
        recorder.save();
        FlightController flightController = MyApplication.getFlightControllerInstance();
        if (flightController != null) {
            flightController.setStateCallback(null);
        }
        recorder.keep = false;
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private OnRecordListener recordListener;

    public interface OnRecordListener {
        void update(int time);
    }

    public void setOnRecordListener(OnRecordListener cb) {
        recordListener = cb;
    }

    private class Recorder {
        private final Thread thread;
        private String date;
        private int time;
        private float distance;
        private float height;
        private float speed;
        private float takeoff;
        private boolean keep = true;

        private Recorder(String date) {
            this.date = date;
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (keep) {
                        try {
                            Thread.sleep(1000);
                            distance += speed;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            thread.start();
        }

        private void setTime(int d) {
            if (d > time) {
                this.time = d;
            }
        }

        private void setHeight(float h) {
            if (h > height)
                this.height = h;
        }

        private void setSpeed(float s) {
            if (s > speed)
                speed = new BigDecimal(Math.sqrt(s)).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();

        }

        private void setTakeoff(float t) {
            this.takeoff = t;
        }

        public void save() {
            if (time == 0)
                return;
            SQLiteDbHelper sqLiteDbHelper = new SQLiteDbHelper(FlightRecorderService.this);
            sqLiteDbHelper.dbInsert(toContentValues());
            keep = false;
            clean();
        }

        private ContentValues toContentValues() {
            ContentValues contentValues = new ContentValues();
            contentValues.put("_date", date);
            contentValues.put("_time", time);
            contentValues.put("_distance", (int) distance);
            contentValues.put("_height", height);
            contentValues.put("_speed", speed);
            contentValues.put("_takeoff", takeoff);
            return contentValues;
        }

        private void clean() {
            date = "";
            time = 0;
            distance = 0;
            height = 0;
            speed = 0;
            takeoff = 0;
        }
    }
}
